﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ServiceOfSansar.Models;
using ServiceOfSansar.Auth;

namespace ServiceOfSansar
{
    [ErrorHandler]
    [ServiceContract(Namespace = "Sansar")]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class Master
    {

        #region Database
        private SansarEntities db;
        public Master()
        {
            db = new SansarEntities();
        }
        ~Master()
        {
            db.Dispose();
        }
        #endregion


        //Хэрэглэгч нэвтрэх
        [OperationContract]
        public Result Login(string UserName, string password)
        {
            var user = db.Users.FirstOrDefault(w => w.Name.Equals(UserName) && w.Password.Equals(password));
            if (user == null)
                return new Result() { Code = 1001, Message = "Нэвтрэх эрхгүй байна!" };

            TokenManager.Kills();
            var token = db.Tokens.FirstOrDefault(w => w.UserId == user.UserId);
            if (token != null)
                return new Result(1003, "Энэ хэрэглэгчээр нэвтэрч орсон байна!");

            return new Result()
            {
                Code = 0,
                Message = TokenManager.Create(user.UserId),
                RetData =user.UserId                
            };
        }

        [OperationContract]
        public Result Logout(int user_id)
        {
            var usr = db.Tokens.FirstOrDefault(w => w.UserId == user_id);
            if (usr != null)
            {
                db.Tokens.DeleteObject(usr);
                db.SaveChanges();
            }
            return new Result() { Code = 0, Message = "Програмаас гарлаа" };
        }

        [OperationContract]
        public List<Permission> MenuList(int RoleId)
        {
            return db.Permissions.ToList();
        }

        [OperationContract]
        public string Test(string name)
        {
            int a = 0;
            int b = 1;
            int c = b / a;
            return "My name is " + name;
        }


    }
}
